package com.ulook.lookplanet.main;

import android.app.Application;
import android.content.SharedPreferences;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.ulook.lookplanet.base.BaseViewModel;
import com.ulook.lookplanet.common.DataFile;
import com.ulook.lookplanet.common.LookPlanetApplication;
import com.ulook.lookplanet.data.model.BaseUser;
import com.ulook.lookplanet.data.model.TUser;
import com.ulook.lookplanet.data.model.Visitor;
import com.ulook.lookplanet.data.repository.MainRepository;
import com.ulook.lookplanet.util.SharedPreUtil;
import com.ulook.lookplanet.util.ThrowException;
import com.ulook.lookplanet.util.net.OkHttpException;
import com.ulook.lookplanet.util.net.ResponseCallback;

/**
 * 描述：
 *
 * @author L1998
 * @data 2021/3/26
 */
public class MainViewModel extends BaseViewModel {

    private MutableLiveData<BaseUser> currUser = new MutableLiveData<>();

    private MainRepository repository;
    public MainViewModel(Application application, MainRepository repository){
        super(application);
        this.repository = repository;
    }

    public LiveData<BaseUser> getCurrUser(){
        return currUser;
    }

    /**
     * 设置当前用户（登陆模式）
     */
    public void setCurrUser(BaseUser baseUser){
        currUser.setValue(baseUser);
        //LookPlanetApplication.setCurrUserId(baseUser.getId());
    }

    /**
     * 验证登陆信息
     */
    public boolean loginCheck(){
        SharedPreferences pref = SharedPreUtil.getSharedPre(DataFile.LOGIN_DATA, getApplication());
        int id = pref.getInt("id", 0);
        String pw = pref.getString("password", null);

        if(id == 0){  // 没有登陆信息
            setCurrUser(new Visitor());
            return false;
        }else{
            TUser user = new TUser();
            user.setId(id);
            setCurrUser(user); //提前设置
            // 再验证
            ResponseCallback callback = new ResponseCallback() {
                @Override
                public void onSuccess(Object res) {
                    //setCurrUser((TUser)res);
                }
                @Override
                public void onFailure(OkHttpException failuer) {
                    setCurrUser(new Visitor());
                    ThrowException.print(failuer, "验证登陆信息失败");
                }
            };
            repository.verifyLoginInfo(id, pw, callback);
        }
        return true;
    }

}
